package com.xuce.controller;

import com.xuce.constant.CookieConstant;
import com.xuce.constant.RedisConstant;
import com.xuce.dto.ResultBean;
import com.xuce.pojo.TUser;
import com.xuce.service.AdminService;
import com.xuce.util.HttpClientUtils;
import com.xuce.util.StringUtil;
import jdk.nashorn.internal.ir.annotations.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Controller
@RequestMapping("user")
@Scope("prototype")
@CrossOrigin(origins = "*", maxAge = 3600,allowCredentials = "true")
public class LoginController {

    @Resource
    private AdminService userService;

    @Autowired
    private RedisTemplate redisTemplate;


    @RequestMapping("showLogin")
    public String showLogin(){
        return "login";
    }

    @RequestMapping("showIndex")
    public String showIndex(){return "index";}

    /**
     * 验证用户名和密码是否正确
     * @return
     */
    @PostMapping("checkLogin")
    @ResponseBody
    public ResultBean checkLogin(
//                TUser user
            String uname,
            String password,
            HttpServletResponse response,
            @CookieValue(name = CookieConstant.USER_CART,required = false)String userCartUuid
    ){

        //交给service去验证用户名和密码是否正确
        ResultBean resultBean = userService.checkLogin(uname,password);
        System.out.println("ResultBean : "+resultBean.getErrno());
//        System.out.println(tUser);
        if(resultBean.getErrno()==0) {
//            //登录成功
//            //生成cookie
//            String uuid = UUID.randomUUID().toString();
//            Cookie cookie = new Cookie(CookieConstant.USER_LOGIN, uuid);
//            //往redis里存
//            //组织键
//            String key = StringUtil.getRedisKey(RedisConstant.USER_LOGIN_PRE, uuid);
//            //把登录成功后的用户对象存入到redis中。以便checkIsLogin接口去判断是否已登录 来使用
//            redisTemplate.opsForValue().set(key, resultBean.getData(), 30, TimeUnit.DAYS);
//            //cookie要发送给客户端
//            cookie.setMaxAge(30 * 24 * 60 * 60);
//            cookie.setPath("/");
//            cookie.setHttpOnly(true);
//            response.addCookie(cookie);
//            System.out.println(response.getHeader("set-cookie"));
//            System.out.println("checkLogin中cookie:  " + cookie.getName() + "," + cookie.getValue());
//            //===========合并购物车的Http请求===========
//            //因为使用HttpClient来发送请求，所以Cookie不能像浏览器发送请求一样自动携带，因此需要我们手动携带Cookie
            //Cookie: user_cart=3b0c227d-9616-4098-b9f3-71cd1405150e; user_login=92cd6c37-36ea-426c-8a72-a826ae9ef579
//            String url = "http://localhost:9085/cart/merge";
//            String url = "http://localhost:9083/user/page_index";
//            StringBuilder sb = new StringBuilder();
//            sb.append(CookieConstant.USER_CART);
//            sb.append("=");
//            sb.append(userCartUuid);
//            sb.append(";");
//            sb.append(CookieConstant.USER_LOGIN);
//            sb.append("=");
//            sb.append(uuid);
//            HttpClientUtils.doGet(url,sb.toString());

//            return "redirect:http://localhost:9083/user/page_index";
            return resultBean;
//            return "index";

        }
        return resultBean;
//        return "login";
    }

    /**
     * 判断用户是否已登录
     */
    @RequestMapping("checkIsLogin")
    @ResponseBody
    public ResultBean checkIsLogin(@CookieValue(name = CookieConstant.USER_LOGIN,required = false) String uuid, HttpServletRequest request){
        //user_login
        //验证我当前是否已登录
//        Cookie[] cookies = request.getCookies();
//        System.out.println("checkIsLogin的uuid"+uuid);
//        System.out.println(request.getHeader("cookie"));
//        System.out.println("cookies ："+cookies);
//        if(cookies!=null){
//            for (Cookie cookie : cookies) {
//                System.out.println("checkIsLogin:"+cookie.getName()+","+cookie.getValue());
//                if(CookieConstant.USER_LOGIN.equals(cookie.getName())){
//                    //找到这个cookie
//                    //拿到cookie的值，组织redis的键
//                    uuid = cookie.getValue();
//                    String redisKey = StringUtil.getRedisKey(RedisConstant.USER_LOGIN_PRE, uuid);
//                    Object o = redisTemplate.opsForValue().get(redisKey);
//                    if(o!=null){
//                        return ResultBean.success(o,"用户已登录");
//                    }
//                }
//            }
//        }
        System.out.println("checkIsLogin的uuid    "+uuid);
        return userService.checkIsLogin(uuid);

    }


    /**
     * 注销
     */
    @RequestMapping("logout")
    @ResponseBody
    public ResultBean logout(@CookieValue(name=CookieConstant.USER_LOGIN,required = false) String uuid,
                       HttpServletResponse response){
        //1.redis中删除
        //uuid有可能是空的，注销成功
        if(uuid!=null&&!"".equals(uuid)){
            String redisKey = StringUtil.getRedisKey(RedisConstant.USER_LOGIN_PRE, uuid);
            redisTemplate.delete(redisKey);
        }
        //2.cookie要删除
        //cookie如何删除？
        //cookie的键  path 是一样的
        Cookie cookie = new Cookie(CookieConstant.USER_LOGIN,"");
        cookie.setMaxAge(0);//删除cookie
        cookie.setPath("/");
        cookie.setHttpOnly(true);//只有后端程序能访问，提高cookie的安全性
        response.addCookie(cookie);
        return ResultBean.success("注销成功");
    }



}
